package com.lysj.bhp.util.sms;

import com.lysj.bhp.exchangerate.service.ExchangeRateService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;


public class MoYunSMSUtil {

    // 发送短信地址
    private final static String SEND_URL = "http://bsr.moyuntv.com/sms/api";
    private final static String KEY = "CHK2Q46IV1R5XJLABN9GWT3M7UOS0EPFZDY8";
    private static Logger log = LoggerFactory.getLogger(MoYunSMSUtil.class);

    public static boolean sendVerifySms(String verify, String phone, String area_code) {
        String content = "【BHP】验证码：" + verify + "，工作人员不会向您索要，请勿向任何人透露！";
        if (!"86".equals(area_code)) {
            content = "【BHP】Your verification code is " + verify;
        }
        String sign = md5(content + KEY);
        Map<String, String> param = new TreeMap<>();
        param.put("area_code", area_code);
        param.put("mobile", phone);
        param.put("tactic", "1");
        param.put("message", content);
        param.put("sign", sign);
        log.debug("发送短信的参数:" + param);
        String result = sendPost(SEND_URL, map2param(param));
        System.out.println(result);
        if (!"1".equals(result)) { //发送失败
            if (result.equals("-1") || result.equals("-2")) {
                log.error("短信发送失败" + result);
            } else {
                log.debug("短信发送失败" + result);
            }
            return false;
        }
        log.debug("短信发送成功!");
        return true;
    }


    public static boolean sendNotice(String phone, String areacode,String content) {
        String sign = md5(content + KEY);
        Map<String, String> param = new TreeMap<>();
        param.put("area_code", areacode);
        param.put("mobile", phone);
        param.put("tactic", "1");
        param.put("message", content);
        param.put("sign", sign);
        log.debug("发送短信的参数:" + param);
        String result = sendPost(SEND_URL, map2param(param));
        System.out.println(result);
        if (!"1".equals(result)) { //发送失败
            if (result.equals("-1") || result.equals("-2")) {
                log.error("短信发送失败" + result);
            } else {
                log.debug("短信发送失败" + result);
            }
            return false;
        }
        log.debug("短信发送成功!");
        return true;
    }






    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是na1=val1&na2=val2的形式。
     * @return 所代表远程资源的响应结果
     */
    private static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out = new PrintWriter(outWriter);
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }


    /**
     * 对一个参数列表签名
     *
     * @param paramMap,参数列表
     * @param keyName,签名秘钥参数名
     * @param key,签名秘钥
     */
    public static void paramSign(Map<String, Object> paramMap, String keyName, String key) {
        StringBuilder paramBuilder = new StringBuilder();
        paramMap.forEach((k, v) -> paramBuilder.append(k).append("=").append(v).append("&"));
        if (!"".equals(keyName)) {// 在参数后附带上签名秘钥
            paramBuilder.append(keyName).append("=").append(key);
        }
        String paramStr = paramBuilder.toString();
        log.debug("signature param string -> " + paramStr);
        String paramSignature = md5(paramStr);
        log.debug("signature result string -> " + paramSignature);
        paramMap.put("signature", paramSignature);

    }


    /**
     * 获取一个字符串的md5值,编码为utf-8
     *
     * @param string
     * @return 32位MD5摘要过后的字符串
     */
    public static String md5(String string) {
        if (string == null || string.trim().equals("")) {
            return null;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] data = digest.digest(string.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.length; i++) {
                String result = Integer.toHexString(data[i] & 0xff);
                String temp = null;
                if (result.length() == 1) {
                    temp = "0" + result;
                } else {
                    temp = result;
                }
                sb.append(temp);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    // 将map转化为字符串参数
    public static String map2param(Map<String, String> paramMap) {
        StringBuilder paramBuilder = new StringBuilder();
        paramMap.forEach((k, v) -> {
            paramBuilder.append(k).append("=").append(v).append("&");
        });

        return paramBuilder.substring(0, paramBuilder.length() - 1);
    }

}
